package com.exception;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import org.springframework.validation.BindingResult;

import com.tunan.utils.ValidationUtils;


public class InvalidParameterMainError extends AbstractMainError {

	private static final long serialVersionUID = 1L;
	
	private static final String CODE = "10";
	private static final String MESSAGE = "非法的参数";
	private static final String SOLUTION = "请查看根据服务接口对参数格式的要求";
	
    public InvalidParameterMainError(String... parameters) {
    	super(CODE, MESSAGE, SOLUTION);
    	setSubErrors(parameters);
    }
    
    public InvalidParameterMainError(Throwable cause, String... parameters) {
    	super(CODE, MESSAGE, SOLUTION, cause);
    	setSubErrors(parameters);
    }
    
    public InvalidParameterMainError(BindingResult result) {
    	super(CODE, MESSAGE, SOLUTION);
    	setSubErrors(ValidationUtils.convert(result));
    }
    
    public InvalidParameterMainError(Map<String, String> parameters) {
    	super(CODE, MESSAGE, SOLUTION);
    	setSubErrors(parameters);
    }
      
    public InvalidParameterMainError(Throwable cause, Map<String, String> parameters) {
    	super(CODE, MESSAGE, SOLUTION, cause);
    	setSubErrors(parameters);
    }

    private void setSubErrors(String... parameters){
    	if(parameters != null && parameters.length > 0){
    		ArrayList<SubError> subErrors = new ArrayList<SubError>();
    		
    		for(String parameter : parameters)
		        subErrors.add(new InvalidParameterSubError(parameter));
    		
    		setSubErrors(subErrors);
    	}
    }
    
    private void setSubErrors(Map<String, String> parameters){
    	if(parameters != null && parameters.size() > 0){
    		ArrayList<SubError> subErrors = new ArrayList<SubError>();
    		
    		Iterator<Map.Entry<String, String>> it = parameters.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry<String, String> parameter = it.next();
				subErrors.add(new InvalidParameterSubError(parameter.getKey(), parameter.getValue()));
			}
    		
    		setSubErrors(subErrors);
    	}
    }
    
}

